'use strict';
const workerMultiByWord = require('./worker-multi-by-word.js');
const FastScanner = require('../../lib/fastscan.js');
const util = require('../../lib/util.js');
module.exports = async (job, done, app) => {
  const start = Date.now();
  const data = job.data;
  if (data) {
    if (data.by_word) {
      return await workerMultiByWord(job, done, app);
    }
    const resultInfo = {};
    const where = {};
    if (data.source) {
      where.source = data.source;
    }
    const workerConfig = app.config.worker || { page_size: 100000, ConcurrentFindNum: 5 };
    for (const categorie_id of data.categorie_ids) {
      const count = await app.defineWords(categorie_id).count({ where });
      app.logger.info(`${data.sign}:  categorie_id:${categorie_id}   find-count:${count}`);
      const pages = Math.ceil(count / workerConfig.page_size);
      for (let index = 0; index < pages; index += workerConfig.ConcurrentFindNum) {
        const queryArr = [];
        for (let num = 0; num < workerConfig.ConcurrentFindNum; num++) {
          if ((num + index) >= pages) {
            break;
          }
          queryArr.push(await app.defineWords(categorie_id).findAll({
            attributes: [ 'word' ],
            where,
            limit: workerConfig.page_size,
            offset: workerConfig.page_size * Math.max(0, (index - 1 + num)),
            raw: true,
          }).then(list => {
            return list.map(ele => {
              return ele.word;
            });
          }));
        }
        const words = await Promise.all(queryArr).then(wordsList => {
          const arr = [];
          for (const wordArr of wordsList) {
            arr.push(...wordArr);
          }
          return arr;
        });
        const scanner = new FastScanner(words);
        for (const textInfo of data.texts) {
          resultInfo[textInfo.key] = Object.assign(resultInfo[textInfo.key] || {}, scanner.hits(textInfo.text));
        }
      }
    }
    await app.redis.set(`detection-result:${data.sign}`, JSON.stringify(resultInfo), 'EX', 48 * 60 * 60);
    if (data.callback_url) {
      for (const [ key, info ] of Object.entries(resultInfo)) {
        const respes = await app.erpPost('save_cite_tort_log', {
          json_content: JSON.stringify({
            goods_id: key,
            word: Object.keys(info),
          }),
        }).catch(err => {
          app.logger.error(`回调ERP API报错:save_cite_tort_log------error:${err.message}`);
        });
        try {
          app.logger.info(`save_cite_tort_log-----respes:${JSON.stringify(respes)}`);
        } catch (err) {
          app.logger.info(`save_cite_tort_log-----respes:${respes}`);
        }
      }
    }
    const end = Date.now();
    app.logger.info(`${data.sign}:start(ms):${start} end(ms):${end}  jg:${end - start} ms result:${JSON.stringify(resultInfo)}`);
    return Promise.resolve(done());
  }
  return Promise.resolve();
};
